function [X,Y,chan]=bciReadGridLayout(fileName)
% [X,Y,chan]=bciReadGridLayout(fileName);
% reads layout file of a grid. If first value in the file is a single
% value, positions will be rotated by the value
    
fH=fopen(fileName);
TLINE=0;
chanCount=0;
theta=0;
X=zeros(1,1000);
Y=zeros(1,1000);
chan = zeros(1000,1);

while ~(TLINE<0),
    % read a line
    TLINE=fgetl(fH);
    if isempty(TLINE),TLINE='#';end    
    % ignore comments
    if isempty(strfind(TLINE,'#')) && ischar(TLINE),
        tmp = str2num(TLINE);
        if length(tmp)==1,
            theta = tmp;
        elseif length(tmp)==3,
            chanCount=chanCount+1;
            chan(chanCount)=tmp(1);
            X(chanCount) = tmp(2);
            Y(chanCount) = tmp(3);
        elseif length(tmp)>0,
            error('Grid layout file error: wrong number of elements.');
        end
    end
end
fclose(fH);
% crop vectors
chan = chan(1:chanCount);
X = X(1:chanCount);
Y = Y(1:chanCount);

% convert degree to radians
theta = theta*pi/180;
% rotate by theta
rotMat = [cos(theta), -sin(theta); sin(theta), cos(theta)];
rotXY = rotMat*[X;Y];
X=rotXY(1,:)';
Y=rotXY(2,:)';